package com.os;

import com.graphics.ImageAnimator;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JPanel;

/**
 *
 * @author Sajarwo Anggai
 */
public class SpriteAnimator extends JPanel implements Runnable {

    private Thread t;
    private int period = 50;        // 0.05 secs
    private ImageAnimator imageAnimator;
    private ArrayList sprite;
    private int width = 50;
    private int height = 50;
    private boolean running = false;

    public void start() {
        setRunning(true);
        t = new Thread(this);
        t.start();
    }

    public void stop() {
        setRunning(false);
        t.interrupt();
    }

    public void playAnim() {
        if (imageAnimator.isStopped()) {
            imageAnimator.resume();
        } else {
            imageAnimator.restartAt(0);
        }
    }

    public void pauseAnim() {
        imageAnimator.stop();
    }

    public void stopAnim() {
        imageAnimator.restartAt(0);
        imageAnimator.stop();
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }

    public void run() {
        while (isRunning()) {
            try {
                Thread.sleep(period);
            } catch (Exception e) {
            }
            imageAnimator.updateTick();
            repaint();
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        // clear the background
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, width, height);
        drawImage(g2d, imageAnimator.getCurrentImage(), 10, 10);
    }

    private void drawImage(Graphics2D g2d, BufferedImage im, int x, int y) {
        g2d.drawImage(im, x, y, this);
    }

    public void setSprite(ArrayList sprite, int delay, boolean started) {
        this.sprite = sprite;
        imageAnimator = new ImageAnimator(period, delay, started, sprite);
    }

    public void setPeriod(int period) {
        this.period = period;
    }

    public int getPeriod() {
        return period;
    }

    public void setSize(int width, int height) {
        this.width = width;
        this.height = height;
    }
}
